package jhta;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.border.LineBorder;

import java.awt.Color;
import java.awt.SystemColor;

import javax.swing.JLayeredPane;
import javax.swing.border.TitledBorder;

//import jhta.MyTableRender;

import javax.swing.UIManager;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

import javax.swing.DefaultComboBoxModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;//달력추가
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;//달력추가
import net.sourceforge.jdatepicker.impl.UtilDateModel;//달력추가

public class RentUpdate extends JInternalFrame {
	
	JavaDBConnection main=new JavaDBConnection();//db연결 목적
	int type=0;//텍스트창에 구분해서 표시해주려고
	int reset=2;//검색창에 마우스 클릭시 초기화 관련 
	String man;//관리자 이름가져오는
	String rentIn;//대여여부 확인, 삭제시 알림해주기 위해
	
	Main mm;//메인으로 RentInput연결하기위해(table갱신 목적)
	DefaultTableModel model;//가운데 큰테이블
	DefaultTableModel model2;//우측아래 검색정보 테이블 학생정보,도서정보
	//MyTableRender render;//테이블 컬럼 길이조정
	TableRowSorter<TableModel> tSoter;
	
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	String str = sf.format(new Date());
	
	private JLabel label;
	private JComboBox comboBox;
	private JTextField search;
	private JButton button;
	private JScrollPane scrollPane;
	private JTable table;
	private JLayeredPane layeredPane_1;
	private JLabel label_4;
	private JButton button_1;
	private JLabel label_6;
	private JTable table_1;
	private JComboBox manager1;
	private JLabel label_7;
	private JTextField lday;
	private JTextField eday;
	private JLabel label_8;
	private JTextField number1;
	private JButton button_2;
	private JLabel label_1;
	private JDatePickerImpl datePicker;//달력 추가
	private JDatePickerImpl datePicker2;//달력 추가
	private SpringLayout springLayout;//달력2 추가
	
	/**
	 * Create the frame.
	 */
	public RentUpdate(Main m) {
		super("대여조회 및 수정",false, true, false, true);
		setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 636, 548);
		getContentPane().setLayout(null);
		getContentPane().add(getLabel());
		getContentPane().add(getComboBox());
		getContentPane().add(getSearch());
		getContentPane().add(getButton());
		getContentPane().add(getScrollPane());
		getContentPane().add(getLayeredPane_1_1());
		
		main.connect();//db연결
		
		this.mm=m;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("조     회");
			label.setHorizontalAlignment(SwingConstants.CENTER);
			label.setBounds(12, 13, 69, 15);
		}
		return label;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			String[] t = {"전체","대여번호","대여제목","대여자","대여일자","반납예정일자","대여중","반납완료"};
			comboBox = new JComboBox(t);
			comboBox.setModel(new DefaultComboBoxModel(new String[] {"전체", "대여번호", "대여제목", "대여자", "대여일자", "반납예정일자","대여중","반납완료"}));
			comboBox.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent ee) {
					String searchKind=(String)ee.getItem();
					
					if(searchKind.equals("대여일자")){
						SimpleDateFormat sd = new SimpleDateFormat("yy/MM/dd");
						search.setText("ex)"+sd.format(new Date())+" 형식으로 해주세요");
						reset=1;
						
					}else if(searchKind.equals("전체")){
						search.setText("전체 대여자가 조회됩니다");
						reset=1;
						
					}else if(searchKind.equals("대여번호")){
						search.setText("번호를 입력하세요");
						reset=1;
						
					}else if(searchKind.equals("대여자")){
						search.setText("이름을 입력하세요");
						reset=1;
						
					}else if(searchKind.equals("반납예정일자")){
						SimpleDateFormat sd = new SimpleDateFormat("yy/MM/dd");
						search.setText(" ex)"+sd.format(new Date())+" 형식으로 해주세요");
						reset=1;
						
					}else if(searchKind.equals("도서제목")){
						search.setText("제목을 입력하세요");
						reset=1;
						
					}else if(searchKind.equals("대여중")){
						search.setText("대여중인 책이 조회됩니다");
						reset=1;
						
					}else if(searchKind.equals("반납완료")){
						search.setText("반납완료된 책이 조회됩니다");
						reset=1;
					}
					
				}
			});
			
			comboBox.setBounds(88, 7, 113, 26);
		}
		return comboBox;
	}
	private JTextField getSearch() {
		if (search == null) {
			search = new JTextField();
			search.addKeyListener(new KeyAdapter() {
				@Override
				public void keyPressed(KeyEvent ev) {
					if(ev.getKeyCode()==KeyEvent.VK_ENTER){
						type();
					}
					
				}
			});
				search.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						if(reset==1){//콤보박스 클릭하고난 뒤 마우스클릭하면 검색text초기화됨, 그이외에 검색시에는 검색text초기화 안됨 
							search.setText("");//검색창 마우스 클릭시 초기화
							reset=0;
						}
					}
				});	
			search.setColumns(10);
			search.setBounds(213, 8, 295, 26);
		}
		return search;
	}
	private JButton getButton() {
		if (button == null) {
			button = new JButton("검색");
			button.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					type();
				}
			});
			button.setBounds(520, 7, 89, 26);
		}
		return button;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			
			scrollPane = new JScrollPane();
			scrollPane.setBounds(12, 39, 598, 279);
//			scrollPane.setViewportView(getTable());
		}
		return scrollPane;
	}
	private JTable getTable() {
		if (table != null) {
			table = new JTable(model);
			table.addMouseListener(new MouseAdapter() {
				@Override
				public void mouseClicked(MouseEvent ee) {
					if(ee.getButton()==1){
						int a=table.getSelectedRow();
						number1.setText(model.getValueAt(a, 0).toString());//대여번호
						lday.setText(model.getValueAt(a, 1).toString());//대여일
						eday.setText(model.getValueAt(a, 4).toString());//반납예정일
						rentIn=model.getValueAt(a, 5).toString();//반납여부
						
						//대여번호를 비교해서 관리자 이름 가져오기
						try{
							String managerName="select bm.name from rent r inner join bookmember bm on r.reg_no=bm.no where r.no="+number1.getText();
							PreparedStatement ptmt=main.getConn().prepareStatement(managerName);
							ResultSet rs=ptmt.executeQuery();
							if(rs.next()){
								managerName=rs.getString(1);
							}
							rs.close();
							ptmt.close();
							
							manager1.setSelectedItem(managerName);//콤보박스에 저장된 이름중에서 선택된다는 것이다
						
						}catch(Exception ex){
							
						}
					}
				}
			});
			
//			String[] t = {"대여번호","대여일","대여자","도서제목","반납예정일","반납일"};
//			model = new DefaultTableModel(t,0);
//			table = new JTable(model);
//			tSoter = new TableRowSorter(model);
//			table.setRowSorter(tSoter);//테이블 정렬
			//테이블 길이조정 관련
//			char[] c={'c','c','l','c'};
//			int[] w={60,70,310,10};
//			render = new MyTableRender(table, c,w);
		}
		return table;
	}
	private JLayeredPane getLayeredPane_1_1() {
		if (layeredPane_1 == null) {
			layeredPane_1 = new JLayeredPane();
			layeredPane_1.setBorder(new TitledBorder(null, "\uC785\uB825\uC815\uBCF4", TitledBorder.LEADING, TitledBorder.TOP, null, null));
			layeredPane_1.setBounds(12, 328, 602, 180);
			layeredPane_1.add(getLabel_4());
			layeredPane_1.add(getButton_1_1());
			layeredPane_1.add(getLabel_6_1());
			layeredPane_1.add(getLday());
			layeredPane_1.add(getTextField_4_1());
			layeredPane_1.add(getLabel_8());
			layeredPane_1.add(getNumber1());
			layeredPane_1.add(getButton_2_1());
			layeredPane_1.add(getLabel_7());
			layeredPane_1.add(getManager1());
			layeredPane_1.add(getLabel_1());
			layeredPane_1.add(getDatePicker());//달력 추가
			layeredPane_1.add(getDatePicker2());//달력 추가
		}
		return layeredPane_1;
	}
	private JLabel getLabel_4() {
		if (label_4 == null) {
			label_4 = new JLabel("반납예정일");
			label_4.setHorizontalAlignment(SwingConstants.RIGHT);
			label_4.setBounds(20, 106, 60, 15);
		}
		return label_4;
	}
	private JButton getButton_1_1() {
		if (button_1 == null) {
			button_1 = new JButton("수정");
			button_1.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					modify();//수정하는 것
					type();//가운데 테이블 정보 불러오기
				}
			});
			button_1.setBounds(263, 22, 153, 79);
		}
		return button_1;
	}
	private JLabel getLabel_6_1() {
		if (label_6 == null) {
			label_6 = new JLabel("도서 사진");
			label_6.setHorizontalAlignment(SwingConstants.CENTER);
			label_6.setBorder(new LineBorder(new Color(0, 0, 0)));
			label_6.setBounds(428, 22, 153, 141);
		}
		return label_6;
	}
	
	private JComboBox getManager1() {
		if (manager1 == null) {
			manager1 = new JComboBox();
			manager1.setBounds(89, 136, 162, 28);
			manager1.addItem("선택하시오");//추가
			type2();//관리자가져오기 //추가
			manager1.addItemListener(new ItemListener() {
				public void itemStateChanged(ItemEvent ee) {
					man=(String) ee.getItem();//클릭한 이름 저장
					
				}
			});
		}
		return manager1;
	}
	private JLabel getLabel_7() {
		if (label_7 == null) {
			label_7 = new JLabel("관리자");
			label_7.setBounds(10, 144, 46, 15);
			label_7.setHorizontalAlignment(SwingConstants.RIGHT);
		}
		return label_7;
	}
	private JTextField getLday() {
		if (lday == null) {
			lday = new JTextField();
			lday.setColumns(10);
			lday.setBounds(89, 60, 116, 28);
		}
		return lday;
	}
	private JTextField getTextField_4_1() {
		if (eday == null) {
			eday = new JTextField();
			eday.setColumns(10);
			eday.setBounds(89, 98, 116, 28);
		}
		return eday;
	}
	
	private JLabel getLabel_8() {
		if (label_8 == null) {
			label_8 = new JLabel("대여번호");
			label_8.setHorizontalAlignment(SwingConstants.RIGHT);
			label_8.setBounds(13, 30, 57, 15);
		}
		return label_8;
	}
	private JTextField getNumber1() {
		if (number1 == null) {
			number1 = new JTextField();
			number1.setEnabled(false);
			number1.setColumns(10);
			number1.setBounds(89, 22, 163, 28);
		}
		return number1;
	}
	private JButton getButton_2_1() {
		if (button_2 == null) {
			button_2 = new JButton("삭제");
			button_2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					try{
						System.out.println(rentIn);
						if(rentIn.equals("대여중")){
							JOptionPane.showMessageDialog(null, "대여중인 책은 삭제가 안됩니다.");
						}else if(rentIn.equals("반납완료")){
							String del="delete from rent where no="+number1.getText();//대여번호 지정후 삭제
							PreparedStatement ptmt=main.getConn().prepareStatement(del);
							ResultSet rs=ptmt.executeQuery();
							
							if(rs.next()){
								JOptionPane.showMessageDialog(null, "삭제되었습니다");
							}
							rs.close();
							ptmt.close();
							
							type();//가운데 테이블 정보 불러오기
							
						}
						
						
					}catch(Exception ex){
						JOptionPane.showMessageDialog(null, "삭제가 안됩니다 다시 확인해주세요");
					}
					

				}
			});
			button_2.setBounds(263, 113, 153, 50);
		}
		return button_2;
	}
	
	public void type(){//가운데 테이블 출력해주는 것
		try{
			
			String sql="";
			if(comboBox.getSelectedItem().equals("전체")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no order by r.no asc";
			}
			else if(comboBox.getSelectedItem().equals("대여번호")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where r.no="+Integer.parseInt(search.getText());
			}
			else if(comboBox.getSelectedItem().equals("대여일자")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where r.ldate like '%"+search.getText()+"%'";
			}
			else if(comboBox.getSelectedItem().equals("대여자")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where bm.name='"+search.getText()+"'";
			}
			else if(comboBox.getSelectedItem().equals("대여제목")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where b.name like '%"+search.getText()+"%'";
			}
			else if(comboBox.getSelectedItem().equals("반납예정일자")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where r.Edate like '%"+search.getText()+"%'";
			}	
			else if(comboBox.getSelectedItem().equals("대여중")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where ddate is null order by r.no asc";
			}
			else if(comboBox.getSelectedItem().equals("반납완료")){
				sql="select r.no, r.ldate, bm.name, b.name, r.edate, r.ddate from rent r inner join bookmember bm on r.member_no=bm.no inner join book b on r.book_no=b.no where ddate is not null order by r.no asc";
			}
			
			PreparedStatement ptmt=main.getConn().prepareStatement(sql);
			ResultSet rs=ptmt.executeQuery();
			
			String[] t = {"대여번호","대여일","대여자","도서제목","반납예정일","반납여부"};
			model = new DefaultTableModel(t,0);
			table = new JTable(model);
//			tSoter = new TableRowSorter(model);
//			table.setRowSorter(tSoter);//테이블 정렬
			
			while(rs.next()){
				Vector vec1=new Vector();
				vec1.add(rs.getInt(1));//대여번호
				vec1.add(rs.getDate(2));//대여일
				vec1.add(rs.getString(3));//대여자
				vec1.add(rs.getString(4));//도서제목
				vec1.add(rs.getDate(5));//반납예정일
				if(rs.getDate(6)==null){
					vec1.add("대여중");
				}else{
					vec1.add("반납완료");
				}
				
				model.addRow(vec1);
			}
			
			scrollPane.setViewportView(getTable());
			rs.close();
			ptmt.close();
		}catch(Exception ex){
			
		}
	}
	
	public void type2(){//관리자 가져오기
		try{
			String sql="select name from bookmember where code_no=2";
			PreparedStatement ptmt=main.getConn().prepareStatement(sql);
			
			ResultSet rs=ptmt.executeQuery();
			while(rs.next()){
				manager1.addItem(rs.getString(1));
			}
			rs.close();
			ptmt.close();
			
		}catch(Exception ex){
			
		}
	}
	
	public void modify(){
		
		try{
//			//이름넣고 이름에 해당하는 번호 가져오기
//			String reNa="select no from bookmember where name='"+member.getText()+"'";
//			
//			PreparedStatement ptmt=main.getConn().prepareStatement(reNa);
//			ResultSet rs=ptmt.executeQuery();
//			if(rs.next()){
//				reNa=rs.getString(1);
//			}
//			rs.close();
//			ptmt.close();
			
//			//수정할 대여번호를 선택한 뒤 가져온 회원번호로 수정한다 
//			String seNa="update rent set member_no="+Integer.parseInt(reNa)+" where no="+Integer.parseInt(number1.getText());
//			PreparedStatement ptmt1=main.getConn().prepareStatement(seNa);
//			ResultSet rs1=ptmt1.executeQuery();
//			if(rs1.next()){
//			}
//			rs1.close();
//			ptmt1.close();
			
			//대여일을 수정한다
			String seld="update rent set ldate=to_date('"+lday.getText()+"')  where no="+Integer.parseInt(number1.getText());//대여일
			PreparedStatement ptmt2=main.getConn().prepareStatement(seld);
			ResultSet rs2=ptmt2.executeQuery();
			if(rs2.next()){
			}
			rs2.close();
			ptmt2.close();
			
			//반납예정일을 수정한다
			String seed="update rent set edate=to_date('"+eday.getText()+"')  where no="+Integer.parseInt(number1.getText());//반납예정일
			PreparedStatement ptmt3=main.getConn().prepareStatement(seed);
			ResultSet rs3=ptmt3.executeQuery();
			if(rs3.next()){
			}
			rs3.close();
			ptmt3.close();
			
			//도서명으로 도서 번호를 받아온다
//			String rene="select no from book where name='"+name1.getText()+"'";
//			PreparedStatement ptmt5=main.getConn().prepareStatement(rene);
//			ResultSet rs5=ptmt5.executeQuery();
//			if(rs5.next()){
//				rene=rs5.getString(1);
//			}
//			rs5.close();
//			ptmt5.close();
			
			//수정할 대여번호를 넣은 뒤 가져온 도서번호로 수정한다 
//			String sene="update rent set book_no="+Integer.parseInt(rene)+" where no="+Integer.parseInt(number1.getText());//아이디저장하기
//			PreparedStatement ptmt6=main.getConn().prepareStatement(sene);
//			ResultSet rs6=ptmt6.executeQuery();
//			if(rs6.next()){
//			}
//			rs6.close();
//			ptmt6.close();
			
			//관리자 이름으로 관리자 번호를 가져온다
			String reme="select no from bookmember m where m.name='"+man+"'";//관리자번호
			PreparedStatement ptmt7=main.getConn().prepareStatement(reme);
			int reme1=0;//받아온 관리자 번호 int형으로 넣기
			ResultSet rs7=ptmt7.executeQuery();
			if(rs7.next()){
				reme1=rs7.getInt(1);
			}
			rs7.close();
			ptmt7.close();
			
			//관리자도 수정
			String seme="update rent set reg_no="+reme1+" where no="+Integer.parseInt(number1.getText());
			PreparedStatement ptmt8=main.getConn().prepareStatement(seme);
			ResultSet rs8=ptmt8.executeQuery();
			if(rs8.next()){
			}
			rs8.close();
			ptmt8.close();
			
			JOptionPane.showMessageDialog(null, "수정이 완료되었습니다");
		}catch(Exception ex){
			JOptionPane.showMessageDialog(null, "정확하게 입력해주세요");
		}
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("대여일자");
			label_1.setHorizontalAlignment(SwingConstants.RIGHT);
			label_1.setBounds(13, 68, 57, 15);
		}
		return label_1;
	}
	
	private JDatePickerImpl getDatePicker(){
		if (datePicker == null) {
			UtilDateModel uModel = new UtilDateModel();
			JDatePanelImpl datePanel = new JDatePanelImpl(uModel);
			datePicker = new JDatePickerImpl(datePanel);
			datePicker.setBorder(null);
			springLayout = (SpringLayout) datePicker.getLayout();
			
			datePicker.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					lday.setText(sf.format((Date)datePicker.getModel().getValue()));
				}
			});
			datePicker.setBackground(UIManager.getColor("Button.background"));
			datePicker.getJFormattedTextField().setVisible(false);
			datePicker.setSize(45, 27);//달력 사이즈
			datePicker.setLocation(202, 60);//달력 위치
			
		}
		return datePicker;
	}
	
	private JDatePickerImpl getDatePicker2(){
		if (datePicker2 == null) {
			UtilDateModel uModel = new UtilDateModel();
			JDatePanelImpl datePanel = new JDatePanelImpl(uModel);
			datePicker2 = new JDatePickerImpl(datePanel);
			datePicker2.setBorder(null);
			springLayout = (SpringLayout) datePicker2.getLayout();
			
			datePicker2.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					eday.setText(sf.format((Date)datePicker2.getModel().getValue()));
				}
			});
			datePicker2.setBackground(UIManager.getColor("Button.background"));
			datePicker2.getJFormattedTextField().setVisible(false);
			datePicker2.setSize(45, 27);//달력 사이즈
			datePicker2.setLocation(202, 98);//달력 위치
			
		}
		return datePicker2;
	}
}
